package com.mentaleye.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.AlipaySignature;
import com.mentaleye.bean.CommonResult;
import com.mentaleye.bean.PayBackBean;
import com.mentaleye.bean.PayBean;
import com.mentaleye.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


@Controller
@RequestMapping({"/webPay"})
public class WebPayController {
    private static Logger logger = LoggerFactory.getLogger(WebPayController.class);


    @RequestMapping("/goToPay")
    public void goToPay(PayBean payBean, HttpServletResponse response) {
        CommonResult commonResult = new CommonResult();
        try {
            String result=    HttpClientUtil.sendPostByJson("http://localhost:9080/pay-mvc/pay/goToPay", JSONObject.toJSONString(payBean));
                commonResult= JSONObject.parseObject(result,CommonResult.class);
            logger.info("支付请求后台返回"+result);
            response.setContentType("text/html;charset=UTF-8");
            if(commonResult.getIsSuccess()){
                response.getWriter().write((String)commonResult.getData());//直接将完整的表单html输出到页面
            }else{
                response.getWriter().write("支付异常");
            }
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            commonResult.setResultMsg("获取支付页面异常");
            logger.error("获取支付页面异常", e);
        }


    }




    @RequestMapping("/payBack")
    @ResponseBody
    public CommonResult payBack(HttpServletRequest request) {
        Map<String, String[]> requestParams = request.getParameterMap();
        //并发锁 确定 5分钟内 只有一次 处理请求
        CommonResult commonResult = new CommonResult();
        try {
            //获取支付宝POST过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
                params.put(name, valueStr);
            }

            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
            //计算得出通知验证结果
            //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
            boolean verify_result = AlipaySignature.rsaCheckV1(params, "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsHuT6gyPi+ht2HULChcl0ARKXfLLAQGMx/frLcPHcI02r853U/5X86CfP001XbRA5/FlzSCId1tEJEbGqYKT9Qi6e2FwE5L7s/YCQp9ezuVvKV10SBiVTb8I0VOwiDTRzV15hShAEAbA8b1yHV2SaNvDBDgnZ6TIs59Ce9LCV1mN1d3n69WEmItiTRdAJh/6puUUdJIcEVACv3UXS5Tz0nY/POnZDYNYgHaYW07mMpPKk3gcwoJ09RbcfHYoMkbXjEIZDZOTCqfS5pJzsx9wsvrirJk8XCuXfb4YzYpnMsgHaabxccmpyjue7GxT4YngD5fzpf02dLRsIMUHk1eSAwIDAQAB", "UTF-8", "RSA2");

            if(verify_result) {//验证成功

                PayBackBean  backBean=new PayBackBean();
                backBean.setParams(params);
                String result=    HttpClientUtil.sendPostByJson("http://localhost:9080/pay-mvc/pay/payBack", JSONObject.toJSONString(backBean));
                logger.info("支付回调后台返回"+result);
                commonResult= JSONObject.parseObject(result,CommonResult.class);
            }

            //验签
            //找不到订单
            // TRADE_FINISHED TRADE_SUCCESS
            //根据流水号查询订单 判断订单状态是否是支付成功了 直接返回提示 支付成功
            //获取流水号 是否能查询到对应的流水数据 流水的状态是否是处理中


        } catch (Exception e) {
            logger.error("获取支付页面异常", e);
        }
        return commonResult;
    }

    @RequestMapping("/toPay")
    public String toPay() {
        return "pay/toPay";
    }
}
